<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>组卷工具</title>
    <link rel="stylesheet" href="selected.css"/>
    <link rel="stylesheet" href="style.css"/>
</head>
<body>
<h1 class="pdf-ignore">已选考题</h1>

<div class="buttons pdf-ignore">
    <button onclick="goBack()">返回</button>
    <button onclick="generatePdf()">导出PDF</button>
</div>

<ul id="selectedList"></ul>

<div class="buttons pdf-ignore">
    <button onclick="goBack()">返回</button>
    <button onclick="generatePdf()">导出PDF</button>
</div>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
<script>
    let currentQuesList = [];

    async function loadSelectedList() {
        currentQuesList = await window.ipcRender.invoke('ques:getSelected');
        renderQuesList(currentQuesList);
        initSortable(); // 拖动重排序
        addDraggingListener(); // 拖拽逻辑判断
    }

    function renderQuesList(list, expandedIds = []) {
        const ul = document.getElementById('selectedList');
        ul.innerHTML = '';

        list.forEach((q, index) => {
            const li = document.createElement('li');
            li.dataset.id = q.id;
            li.className = 'ques-item';
            // 判断是否应该展开
            if (expandedIds.includes(q.id)) {
                li.classList.add('expanded');
            } else {
                li.classList.add('collapsed');
            }

            // 序号
            const id = document.createElement('label');
            id.className = 'ques-id';
            id.innerHTML = `<strong>${index + 1}. </strong>`;

            // 题干
            const text = document.createElement('span');
            text.className = 'ques-text';
            text.textContent = q.content;
            // 可能的图片
            if (q.content_img) {
                const contentImg = document.createElement('img');
                contentImg.className = 'content-img';  // 你可以加样式控制尺寸
                contentImg.src = q.content_img;
                text.appendChild(document.createElement('br')); // 换行
                text.appendChild(contentImg);
            }

            // 选项
            const optionList = document.createElement('ul');
            optionList.className = 'option-list';
            ['a', 'b', 'c', 'd'].forEach(opt => {
                const text = q[`choice_${opt}`];
                const img = q[`choice_${opt}_img`];
                if (!text && !img) return; // 跳过空选项
                const optLi = document.createElement('li');

                // 判断是否为正确答案
                if (opt.toLowerCase() === q.answer.toLowerCase()) {
                    optLi.classList.add('correct-option');
                }

                const label = document.createElement('span');
                label.textContent = `${opt.toUpperCase()}.  ${text || ''}`;
                optLi.appendChild(label);
                if (img) {
                    const image = document.createElement('img');
                    image.className = 'option-img';
                    image.src = img;
                    optLi.appendChild(image);
                }
                optionList.appendChild(optLi);
            });

            const content = document.createElement('span');
            content.className = 'ques-content';

            content.appendChild(text);
            content.appendChild(optionList);

            const wrapper = document.createElement('div');
            wrapper.className = 'item-wrapper';
            wrapper.appendChild(content);

            // 删除按钮
            const deleteBtn = document.createElement('button');
            deleteBtn.className = 'delete-btn pdf-ignore';
            deleteBtn.innerHTML = '×';
            deleteBtn.title = '移除本题';
            deleteBtn.onclick = (e) => {
                e.stopPropagation();  // 防止触发折叠展开
                const idToRemove = q.id;
                currentQuesList = currentQuesList.filter(item => item.id !== idToRemove);
                renderQuesList(currentQuesList);
                window.ipcRender.send('ques:updateSelectedOrder', currentQuesList.map(q => q.id));
            };
            li.appendChild(deleteBtn);

            li.appendChild(id)
            li.appendChild(wrapper);
            ul.appendChild(li);
        });
    }

    function initSortable() {
        const ul = document.getElementById('selectedList');
        new Sortable(ul, {
            animation: 150,
            onEnd: () => {
                // 收集当前展开的题目 ID（保证重新渲染不改变展开状态）
                const expandedIds = Array.from(ul.children)
                    .filter(li => li.classList.contains('expanded'))
                    .map(li => parseInt(li.dataset.id));

                const newOrderIds = Array.from(ul.children).map(li => parseInt(li.dataset.id));
                // 更新 currentQuesList 顺序
                currentQuesList = newOrderIds.map(id => currentQuesList.find(q => q.id === id));
                // 重新渲染 + 更新编号
                renderQuesList(currentQuesList, expandedIds);
                // 通知主进程更新排序
                window.ipcRender.send('ques:updateSelectedOrder', newOrderIds);
            }
        });
    }

    function addDraggingListener() {
        const ul = document.getElementById('selectedList');
        let isDragging = false;

        ul.addEventListener('mousedown', () => {
            isDragging = false;
        });
        ul.addEventListener('mousemove', () => {
            isDragging = true;
        });

        ul.addEventListener('click', (e) => {
            if (isDragging) return; // 拖拽点击，忽略
            const li = e.target.closest('.ques-item');
            if (!li || !ul.contains(li)) return;
            li.classList.toggle('collapsed');
            li.classList.toggle('expanded');
        });
    }

    function goBack() {
        window.location.href = 'index.html';
    }

    async function generatePdf() {
        // 隐藏无关元素
        const controls = document.querySelectorAll('.pdf-ignore');
        controls.forEach(el => el.style.display = 'none');
        // 添加导出标记，方便修改样式
        document.body.classList.add('pdf-exporting');

        const result = await window.ipcRender.invoke('ques:generatePdf');

        // 恢复页面
        document.body.classList.remove('pdf-exporting');
        controls.forEach(el => el.style.display = '');

        if (result.status === 'success') {
            alert('导出成功！');
        } else if (result.status === 'cancelled') {
            // 用户主动取消
        } else {
            alert('导出失败：' + (result.message || '未知错误'));
        }
    }

    // （页面加载完成后）初始化已选考题列表
    window.addEventListener('DOMContentLoaded', loadSelectedList);
</script>
</body>
</html>
